<template>
  <div class="menu-creator">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="菜单名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入菜单名称，如：库存管理"
          clearable
        />
        <div class="form-tip">
          系统将根据菜单名称自动生成路径和组件名
        </div>
      </el-form-item>

      <el-form-item label="选择图标" prop="icon">
        <div class="icon-selector">
          <el-input
            v-model="form.icon"
            placeholder="选择图标"
            readonly
            class="icon-input"
          >
            <template #prefix>
              <i v-if="form.icon" :class="form.icon" class="selected-icon"></i>
            </template>
            <template #suffix>
              <el-button text @click="showIconDialog = true">
                <i class="fa fa-search"></i>
              </el-button>
            </template>
          </el-input>
        </div>
      </el-form-item>

      <el-form-item label="父菜单" prop="parent">
        <el-select
          v-model="form.parent"
          placeholder="选择父菜单"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="option in parentOptions"
            :key="option.id"
            :label="option.name"
            :value="option.id"
          />
        </el-select>
        <div class="form-tip">
          选择父菜单可创建子菜单，留空则创建顶级菜单
        </div>
      </el-form-item>

      <el-form-item label="菜单描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入菜单功能描述"
        />
      </el-form-item>

      <!-- 预览区域 -->
      <el-form-item label="路径预览">
        <div class="preview-info">
          <div class="preview-item">
            <label>生成路径：</label>
            <code>{{ previewPath }}</code>
          </div>
          <div class="preview-item">
            <label>组件名：</label>
            <code>{{ previewComponent }}</code>
          </div>
          <div class="preview-item">
            <label>权限代码：</label>
            <code>{{ previewPermission }}</code>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="$emit('cancel')">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        创建菜单
      </el-button>
    </div>

    <!-- 图标选择对话框 -->
    <el-dialog
      v-model="showIconDialog"
      title="选择图标"
      width="800px"
      :append-to-body="true"
    >
      <IconSelector
        :selected="form.icon"
        @select="handleIconSelect"
        @close="showIconDialog = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import IconSelector from './IconSelector.vue'
import { dynamicMenuApi } from '@/api/dynamicMenu'

// Props
interface Props {
  parentOptions: Array<{ id: any; name: string }>
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<InstanceType<typeof ElForm>>()
const showIconDialog = ref(false)
const submitting = ref(false)

const form = reactive({
  name: '',
  icon: 'fa-file',
  parent: null,
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '菜单名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ]
}

// 计算属性 - 预览信息
const previewPath = computed(() => {
  if (!form.name) return '/your-menu-path'
  
  // 简单的中文转英文映射
  const chineseToEnglish: Record<string, string> = {
    '管理': 'management',
    '系统': 'system',
    '用户': 'user',
    '主机': 'host',
    '服务': 'service',
    '配置': 'config',
    '监控': 'monitor',
    '日志': 'log',
    '审计': 'audit',
    '权限': 'permission',
    '角色': 'role',
    '组': 'group',
    '菜单': 'menu',
    '设置': 'settings',
    '数据': 'data',
    '文件': 'file',
    '网络': 'network',
    '安全': 'security',
    '备份': 'backup',
    '报表': 'report',
    '任务': 'task',
    '项目': 'project',
    '资源': 'resource',
    '库存': 'inventory',
    '订单': 'order',
    '财务': 'finance'
  }
  
  let englishName = form.name
  Object.entries(chineseToEnglish).forEach(([chinese, english]) => {
    englishName = englishName.replace(new RegExp(chinese, 'g'), english)
  })
  
  // 移除非字母数字字符，转换为小写，用连字符连接
  englishName = englishName
    .replace(/[^a-zA-Z0-9\u4e00-\u9fff]/g, '-')
    .replace(/[\u4e00-\u9fff]/g, '')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')
    .toLowerCase() || 'custom-page'
  
  // 获取父菜单路径
  const parentOption = props.parentOptions.find(opt => opt.id === form.parent)
  if (parentOption && parentOption.id) {
    // 这里简化处理，实际应该从API获取父菜单的完整路径
    return `/parent-path/${englishName}`
  }
  
  return `/${englishName}`
})

const previewComponent = computed(() => {
  if (!form.name) return 'YourMenuComponent'
  
  const path = previewPath.value.replace(/^\//, '').replace(/\//g, '-')
  return path.split('-').map(word => 
    word.charAt(0).toUpperCase() + word.slice(1)
  ).join('')
})

const previewPermission = computed(() => {
  if (!form.name) return 'your.menu.view'
  
  const path = previewPath.value.replace(/^\//, '').replace(/\//g, '.')
  return `${path}.view`
})

// 方法
const handleIconSelect = (icon: string) => {
  form.icon = icon
  showIconDialog.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    const response = await dynamicMenuApi.createMenu({
      name: form.name,
      icon: form.icon,
      parent: form.parent,
      description: form.description
    })
    
    if (response.success) {
      ElMessage.success('菜单创建成功！')
      emit('success')
      resetForm()
    } else {
      ElMessage.error(response.message || '创建菜单失败')
    }
  } catch (error) {
    console.error('创建菜单失败:', error)
    ElMessage.error('创建菜单失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    name: '',
    icon: 'fa-file',
    parent: null,
    description: ''
  })
}

// 监听名称变化，自动设置描述
watch(() => form.name, (newName) => {
  if (newName && !form.description) {
    form.description = `${newName}功能页面`
  }
})
</script>

<style lang="scss" scoped>
.menu-creator {
  .form-tip {
    font-size: 12px;
    color: rgba(255, 255, 255, 0.6);
    margin-top: 4px;
  }
  
  .icon-selector {
    .icon-input {
      .selected-icon {
        color: #00eaff;
        font-size: 16px;
      }
    }
  }
  
  .preview-info {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 6px;
    padding: 12px;
    
    .preview-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      label {
        color: rgba(255, 255, 255, 0.8);
        width: 80px;
        flex-shrink: 0;
        font-size: 12px;
      }
      
      code {
        background: rgba(0, 234, 255, 0.1);
        color: #00eaff;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 12px;
        font-family: 'Courier New', monospace;
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
  }
}

// Element Plus 样式覆盖
:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9);
}

:deep(.el-input__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  
  &::placeholder {
    color: rgba(255, 255, 255, 0.5);
  }
}

:deep(.el-textarea__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  
  &::placeholder {
    color: rgba(255, 255, 255, 0.5);
  }
}

:deep(.el-select) {
  .el-input__inner {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #fff;
  }
}

:deep(.el-button) {
  &.el-button--primary {
    background: linear-gradient(135deg, #00eaff, #0099cc);
    border: none;
    
    &:hover {
      background: linear-gradient(135deg, #00d4e6, #0088bb);
    }
  }
}
</style>
